package com.defangit.production.orm;

import com.defangit.production.bll.ProcessBll;
import com.defangit.production.domain.ProcessSection;
import laogen.hibernate.CommonFinder;
import laogen.hibernate.CommonService;
import laogen.lang.exception.ParameterNotValidException;
import org.hibernate.Criteria;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
/**
 * Created by zhangfagen on 2018/6/5.
 */
public class ProcessService extends CommonService<ProcessSection>  implements ProcessBll {
    public ProcessSection addProcess(ProcessSection process) {
        if(process==null) throw ParameterNotValidException.nullParameter("工序");
        add(process);
        commitSession();
        return get(process.getId()).orElseThrow(()->
            ParameterNotValidException.zeroIdOrEntityNonExist("工序"+process.getId())
        );
    }

    public ProcessSection updateProcess(ProcessSection process) {
        if(process==null) throw ParameterNotValidException.nullParameter("要更改的工序");
        merge(process);
        commitSession();
        return get(process.getId()).orElseThrow(()->
            ParameterNotValidException.zeroIdOrEntityNonExist("工序"+process.getId())
        );
    }

    public boolean deleteProcess(int id) {
        return false;
    }

    public ProcessFinder findUsed() {
        return findAll().used(true);
    }

    public ProcessFinder findAll() {
        return new ProcessFinderImpl(detachedAll());
    }

    public class ProcessFinderImpl extends CommonFinder<ProcessSection> implements ProcessFinder{
        private DetachedCriteria criteria;
        ProcessFinderImpl(DetachedCriteria criteria){
            this.criteria=criteria;
        }
        public Criteria getCriteria() {
            return criteria.getExecutableCriteria(getSession()).addOrder(Order.desc("id"));
        }

        public DetachedCriteria getDetachedCriteria() {
            return criteria;
        }

        public ProcessFinder used(Boolean used) {
            if(used!=null){
                this.criteria=this.criteria.add(Restrictions.eq("notUsed",!used));
            }
            return this;
        }
    }
}
